import Message from './message.svelte';

export default Message;

type Options = {
	loading?: boolean;
	message?: string;
	duration?: number;
	type: 'primary' | 'success' | 'danger' | 'warning' | 'info' | 'light';
};

export type COLOR_TYPE = 'primary' | 'success' | 'warning' | 'danger';

export type MsgOptions = Options;

class MessageBox {
	#instance: Message;
	constructor(options: Record<string, never>) {
		this.#instance = new Message({
			target: document.body,
			props: {
				...options
			}
		});
		this.#instance.$on('close', () => {
			this.destroy();
		});
	}

	destroy() {
		this.#instance?.$destroy();
	}

	update_loading_to_success(text: string = 'handle success', duration: number = 1000) {
		const resetData = {
			loading: false,
			success: true,
			type: 'light',
			message: text,
			duration
		};
		this.#instance.$set(resetData as unknown as Record<string, never>);
	}

	update_loading_to_error(text: string = 'handle error', duration: number = 1000) {
		const resetData = {
			loading: false,
			error: true,
			type: 'danger',
			message: text,
			duration
		};
		this.#instance.$set(resetData as unknown as Record<string, never>);
	}
}

export const createMessage = (options: Options) => {
	return new MessageBox(options as unknown as Record<string, never>);
};

export type ShowMsgResultType = {
	instance: MessageBox;
	close: () => void;
	error: () => void;
};

export const showLoading = (() => {
	let instance: MessageBox | null = null;

	return (message: string = 'Loading...') => {
		if (instance) {
			instance.destroy();
		}

		instance = createMessage({ loading: true, message, type: 'light' });

		return {
			instance,
			close: () => instance!.update_loading_to_success(),
			error: () => instance!.update_loading_to_error()
		};
	};
})();
